package com.fingard.dsp.bank.directbank.cmb01;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.paynotice.NoticeDataHelper;
import com.fingard.dsp.bank.dbobj.paynotice.SinglePayNotice;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.DirectHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.dsp.bank.directbank.cmb01.receiptpro.CMB01TaskReceiptPro;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.ReceiptFileSaveHelper;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FormSubmit;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CMB01ScheduleTask extends CMB01Base implements IScheduleTask {

    public void execTask(TaskTimerSet timerSet) {
        try {
            if (timerSet.taskNameList.toLowerCase().contains("getnewnotice")) {
                getNewNotice();
            }
            if (timerSet.taskNameList.toLowerCase().contains("pushreceipt")) {
                pushReceipt();
            }
            if (timerSet.taskNameList.toLowerCase().contains("pushthreadpoolreceipt")) {
                pushThreadPoolReceipt();
            }
            if (timerSet.taskNameList.toLowerCase().contains("downreceiptpro")) {
                CMB01TaskReceiptPro taskReceiptPro = new CMB01TaskReceiptPro();
                taskReceiptPro.reqHeader = this.reqHeader;
                taskReceiptPro.bankFront = this.bankFront;
                taskReceiptPro.setSbLog(this.sbLog);
                taskReceiptPro.setLogFlushTime(this.logFlushTime);
                taskReceiptPro.downReceipt(timerSet);
            }
        } catch (Exception ex) {
            this.WriteBankLogLn(ex);
        }
    }

    public void pushThreadPoolReceipt() {
        try {
            //定义参数
            if (StringHelper.isNullOrEmpty(bankFront.bankReceiptMainDir)) {
                WriteBankLogLn("未配置bankReceiptMainDir");
                return;
            }
            int tmpFileCount = 0;//上传成功文件数
            int moveFileCount = 0;//移动成功文件数
            List<ReceiptMapping> listFile=new ArrayList<ReceiptMapping>();//回单文件列表
            Map<String, Map<String, ReceiptMapping>> mapNO = null;//根据账号-日期存回单记录列表，ReceiptMapping根据业务参考号存回单数据
            List<StringBuilder> jsonList = new ArrayList<StringBuilder>();//json集合，用于统计全部回单数据，推送ats
            File receiptDir = new File(bankFront.bankReceiptMainDir);
            if (!receiptDir.exists()) {
                WriteBankLogLn("不存在招行回单目录" + bankFront.bankReceiptMainDir);
                return;
            }
            //获取前置目录全部回单文件
            File[] receiptFiles = receiptDir.listFiles();
            WriteBankLogLn("========1、遍历招行前置回单目录，获取待上传文件数："+receiptFiles.length+"，开始进行处理========");
            //遍历招行前置回单目录，获取回单集合
            for (File receiptFile : receiptFiles) {
                String eachName = receiptFile.getName();//回单名
                if (eachName.toLowerCase().endsWith(".jpg")) {
                    String[] finfo = eachName.split("_");
                    if (finfo.length >= 3) {
                        String actNum = finfo[0];//账号
                        String fdate = finfo[1].split("-")[0];//日期
                        String receiptNO = finfo[2].split("\\.")[0];//打印实例号
                        String key1 = actNum + "-" + fdate;
                        if (mapNO == null) {
                            mapNO = new HashMap<String, Map<String, ReceiptMapping>>();
                        }
                        //账号一天的回单报文只处理一次
                        if (!mapNO.containsKey(key1)) {
                            String printFlagStr = getValueAsString("printFlag");
                            if (StringHelper.isNullOrEmpty(printFlagStr)) {
                                WriteBankLogLn2("配置文件缺失招行回单打印标志配置（1:未打印，2:已打印）:<printFlag></printFlag>，当前使用默认值1。");
                                printFlagStr = "1";
                            } else if (!"1".equals(printFlagStr) && !"2".equals(printFlagStr) && !"1,2".equals(printFlagStr)) {
                                throw new Exception("配置文件招行回单打印标志配置不规范：" + printFlagStr);
                            }
                            //打印标识
                            String[] printFlags = printFlagStr.split(",");
                            //处理一天的回单报文
                            Map<String, ReceiptMapping> mapDetail=dealWithReceiptXml(fdate,printFlags,actNum);
                            //一天的回单报文存入map
                            mapNO.put(key1, mapDetail);
                        }
                        //根据账号-日期，取出回单记录列表
                        Map<String, ReceiptMapping> mapDetail2 = mapNO.get(key1);
                        if (mapDetail2.containsKey(receiptNO)) {//存在当前文件的打印实例号
                            ReceiptMapping rcptMp = mapDetail2.get(receiptNO);
                            rcptMp.srcFile=receiptFile.getName();//回单名
                            rcptMp.receiptFile =receiptFile.getPath();//回单相对路径
                            listFile.add(rcptMp);
                        } else {
                            WriteBankLogLn("文件" + eachName + "找不到对应的业务参考号，暂不推送");
                        }
                    } else {
                        WriteBankLogLn("文件名" + eachName + "不符合预期");
                        receiptFile.delete();
                        continue;
                    }
                }
            }
            WriteBankLogLn("========2、获取待上传回单文件信息完成，处理数："+listFile.size()+"，开始上传回单========");
            //开始处理回单集合
            if(listFile!=null && listFile.size()>0){
                //开始上传回单list
                Map<String,ReceiptMapping> upSucReceiptMap=uploadFileByThreadPool(listFile);
                WriteBankLogLn("========3、上传回单成功数："+upSucReceiptMap.size()+"，开始拼接json串========");
                //判断上传成功的map数据
                if(upSucReceiptMap!=null && upSucReceiptMap.size()>0){
                    //逐个拼接json串，存入jsonlist，移动前置共享目录下的回单文件至前置共享下receipt目录(暂不做删除操作)
                    for(Map.Entry<String,ReceiptMapping> m : upSucReceiptMap.entrySet()){
                        //拼接json串
                        ReceiptMapping rcptMp=m.getValue();//回单
                        StringBuilder json = new StringBuilder();
                        json.append("{");
                        json.append("\"actNum\":\"" + rcptMp.ownAct + "\",");
                        String actCur = getBankConfig().getMapValueByKey("elereceiptAccountInfo",rcptMp.ownAct);
                        if (StringHelper.isNullOrEmpty(actCur)){
                            actCur = "1";
                        }
                        json.append("\"actCur\":\"" + actCur + "\",");
                        json.append("\"receiptCode\":\"" + rcptMp.receiptNo + "\",");
                        json.append("\"receiptType\":\"" + "" + "\",");
                        json.append("\"receiptState\":\"" + "" + "\",");
                        json.append("\"oppActName\":\"" + rcptMp.oppActName + "\",");
                        json.append("\"oppActNum\":\"" + rcptMp.oppActNum + "\",");
                        json.append("\"moneyway\":\"" + rcptMp.moneyWay + "\",");
                        json.append("\"amount\":\"" + rcptMp.amount + "\",");
                        json.append("\"tranSeqNo\":\"" + rcptMp.busRef + "\",");
                        json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                        json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(String.valueOf(rcptMp.busDate))) + "\",");
                        json.append("\"filePath\":\"" + m.getKey() + "\",");//文件路径
                        json.append("\"fileType\":\"2\"");
                        json.append("},");
                        jsonList.add(json);
                        tmpFileCount++;
                        //移动回单文件
                        File file=new File(rcptMp.receiptFile);
                        if(file.exists()){
                            String movePath=file.getParentFile()+File.separator+"success"
                                    +File.separator+String.valueOf(rcptMp.busDate)+File.separator+file.getName();
                            if(FileHelper.existFile(movePath)){
                                WriteBankLogLn("文件"+file.getPath()+"在移动文件目录"+movePath+"存在，删除");
                                FileHelper.deleteFileIfExists(file.getPath());
                            }else {
                                if(FileHelper.renameTo(file.getPath(),movePath)){
                                    WriteBankLogLn("文件"+file.getPath()+"移动至"+movePath);
                                    moveFileCount++;
                                }
                            }
                        }
                    }
                }
                WriteBankLogLn("========4、成功拼接json串数：" + tmpFileCount+"，成功移动了" + moveFileCount + "个文件，开始推送ats========");
                //分批推送ats，一批500，按原逻辑处理
                if (tmpFileCount > 0 && jsonList.size() > 0) {
                    String sendStr = null;
                    if(this.getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                        sendStr = "tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[";
                    }else{
                        sendStr = "transType=downloadreceipt&data={\"rows\":[";
                    }
                    StringBuilder sendJson = new StringBuilder();
                    String strValue = getBankConfig().getValueAsString("receiptDataCount");
                    if (StringHelper.isNullOrEmpty(strValue)) {
                        strValue = "500";
                    }
                    Integer receiptDataCount = Integer.valueOf(strValue);
                    for (int i = 0; i < jsonList.size(); i++) {
                        if ((i + 1) % receiptDataCount == 0 || i == jsonList.size() - 1) {
                            jsonList.get(i).deleteCharAt(jsonList.get(i).length() - 1);
                            sendJson.append(jsonList.get(i));
                            sendJson.append("]}");
                            String[] data = sendToATS(sendStr + sendJson.toString());
                            if (data[0].length() == 0 && "ok".equals(data[1])) {
                                WriteBankLogLn("========5、推送数据到ATS成功" + ((i + 1) % receiptDataCount > 0
                                        ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据========");
                            } else {
                                WriteBankLogLn("========5、推送数据到ATS失败" + ((i + 1) % receiptDataCount > 0
                                        ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请检查日志========");
                            }
                            sendJson = new StringBuilder();
                        } else {
                            sendJson.append(jsonList.get(i));
                        }
                    }
                } else {
                    WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
                }
            }else {
                WriteBankLogLn("暂无要处理的回单文件");
            }
        }catch (Exception e){
            WriteBankLogLn(e);
        }
    }
    
	private static long zeroNeedUpCount = 0;//连续需上传记录数为0的次数
	private static Date lastDoUpTime = null;
	
	public static void resetZeroCount(){
		zeroNeedUpCount = 0;
	}
	
	private long getDalayMin(){
		if(zeroNeedUpCount>=10){
			return 30;
		}else{
			long dalayMin = zeroNeedUpCount*3;
			if(dalayMin>30){
				dalayMin = 30;
			}
			return dalayMin;
		}
	}

    public void pushReceipt() {
        String uploadType=SmbFileUtil.getUploadType();
        try {
        	if(zeroNeedUpCount > 0){
				long dalayMin = getDalayMin();
				double extraDelay = 60*dalayMin;
				double diffSecs = DateHelper.getDifferSecs(new Date(), lastDoUpTime);
				if(diffSecs<extraDelay){
					return;
				}
			}
			lastDoUpTime = new Date();
        	
        	
            if (StringHelper.isNullOrEmpty(bankFront.bankReceiptMainDir)) {
                WriteBankLogLn("未配置bankReceiptMainDir");
                return;
            }
            File receiptDir = new File(bankFront.bankReceiptMainDir);
            if (!receiptDir.exists()) {
                WriteBankLogLn("不存在招行回单目录" + bankFront.bankReceiptMainDir);
                return;
            }
            ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
            if (!saveHelper.checkSet(this.sbLog, "308")) {
                return;
            }
            File[] receiptFiles = receiptDir.listFiles();
            int tmpFileCount = 0;
            ArrayList<File> listToDelete = new ArrayList<File>();
            DataFileHelper dFileHelper = null;

            //根据账号-日期存回单记录列表，ReceiptMapping根据业务参考号存回单数据
            HashMap<String, HashMap<String, ReceiptMapping>> mapNO = null;


            //ArrayList<String> unknowRcptType = new ArrayList<String>();
            //记录不存在的回单数据文件，用于过滤消息，不存在的同一个文件日志仅输出一次
            HashMap<String, String> unExistDataFile = new HashMap<String, String>();
            List<StringBuilder> jsonList = new ArrayList<StringBuilder>();
            StringBuilder json = null;
            boolean receiptUploadShared = this.getBankConfig().getValueAsBool("receiptUploadShared");
            for (File receiptFile : receiptFiles) {//遍历招行前置回单目录
                String eachName = receiptFile.getName();
                if (eachName.toLowerCase().endsWith(".jpg")) {
                    Date lastMdDate = new Date(receiptFile.lastModified());
                    double diffSecs = DateHelper.getDifferSecs(new Date(), lastMdDate);
                    if (diffSecs < 2) {//大于2秒的先不传
                        //WriteBankLogLn("文件" + eachName + "最后更新时间离当前时间小于2秒，暂不推送");
                        continue;
                    }
                    String[] finfo = eachName.split("_");
                    if (finfo.length >= 3) {
                        if (dFileHelper == null) {
                            dFileHelper = new DataFileHelper(this);
                        }
                        if (mapNO == null) {
                            mapNO = new HashMap<String, HashMap<String, ReceiptMapping>>();
                        }
                        String actNum = finfo[0];
                        String[] filedates = finfo[1].split("-");
                        String fdate = filedates[0];
                        String[] filereceipt = finfo[2].split("\\.");
                        String receiptNO = filereceipt[0];//打印实例号
                        String key1 = actNum + "-" + fdate;
                        if (!mapNO.containsKey(key1)) {
                            HashMap<String, ReceiptMapping> mapDetail = new HashMap<String, ReceiptMapping>();
                            String printFlagStr = getValueAsString("printFlag");
                            if (StringHelper.isNullOrEmpty(printFlagStr)) {
                                WriteBankLogLn2("配置文件缺失招行回单打印标志配置（1:未打印，2:已打印）:<printFlag></printFlag>，当前使用默认值1。");
                                printFlagStr = "1";
                            } else if (!"1".equals(printFlagStr) && !"2".equals(printFlagStr) && !"1,2".equals(printFlagStr)) {
                                throw new Exception("配置文件招行回单打印标志配置不规范：" + printFlagStr);
                            }
                            String[] printFlags = printFlagStr.split(",");
                            for (String printFlag : printFlags) {
                                String dataFilePath = dFileHelper.getBankReceiptDataFile(Format.Date8Format.parse(fdate), printFlag + "_" + actNum);
                                File dataFile = new File(dataFilePath);
                                if (!dataFile.exists()) {
	                                if(dataFilePath.endsWith(".txt")){
	                                	dataFilePath = dataFilePath.replace(".txt", ".tmp.txt");
	                                }else{
	                                	dataFilePath += ".tmp";
	                                }
	                                dataFile = new File(dataFilePath);
                                }
                                
                                if (dataFile.exists()) {
                                    String fcontent = FileHelper.readToString(dataFile, FGBiz.dspCenter.charset);
                                    XmlTextReader xmlReader = new XmlTextReader(fcontent);

                                    while (xmlReader.read("/CMBSDKPGK/CPRRCSNDX1")) {
                                        String ISTNBR = StringHelper.getFirstNotEmpty(xmlReader.readedXElement.getSingleText("ISTNBR"), xmlReader.readedXElement.getSingleText("PRTINS"));//打印实例号
                                        if (StringHelper.hasAnyChar(ISTNBR)) {//只要有打印实例号
                                            String[] refList = new String[8];
                                            refList[0] = ISTNBR;
                                            refList[1] = xmlReader.readedXElement.getSingleTextNotNull("NARTX1");//对应历史明细YURREF
                                            refList[2] = xmlReader.readedXElement.getSingleTextNotNull("SEQNBR");
                                            refList[3] = xmlReader.readedXElement.getSingleTextNotNull("BUSNBR");//对应历史明细NAREXT
                                            // TODO: 2019/7/17  会导致推送远程目录失败
//                                            refList[3] = xmlReader.readedXElement.getSingleTextNotNull("TRSREF");
                                            refList[4] = xmlReader.readedXElement.getSingleTextNotNull("TRXSET");
                                            refList[5] = xmlReader.readedXElement.getSingleTextNotNull("TRSNBR");
                                            refList[6] = xmlReader.readedXElement.getSingleTextNotNull("TSKNBR");
                                            //防止标签AGFEERRCZ2数据无法推送
                                            refList[7] = xmlReader.readedXElement.getSingleTextNotNull("TRSSEQ");
//                                            String firstStr = StringHelper.getFirstNotEmptyTrim(refList);//NARTX1,BUSNBR,SEQNBR,TRSREF

                                            if (StringHelper.hasAnyChar(ISTNBR) && !mapDetail.containsKey(ISTNBR)) {
                                                ReceiptMapping eachRcptMp = new ReceiptMapping();
                                                eachRcptMp.busRef = ISTNBR;
                                                for (int i = 0; i < refList.length; i++) {//潜在多个关联号也一并添加
                                                    if (!ISTNBR.equals(refList[i]) && StringHelper.hasAnyChar(refList[i])) {
                                                        eachRcptMp.addOtherBusRef(refList[i], eachRcptMp.receiptNo);
                                                    }
                                                }
                                                eachRcptMp.bank = "308";
                                                String eachAmt = "";
                                                String[] amtColumns = new String[]{"TRSAMT", "INTAMT", "TRXAMT", "AMTTRS", "ACTAMT", "BILAMT", "OPNAMT", "TRXAM1", "FEEAMT"};
                                                for (int i = 0; i < amtColumns.length; i++) {
                                                    eachAmt = xmlReader.readedXElement.getSingleTextNotNull(amtColumns[i]);
                                                    if (StringHelper.hasAnyChar(eachAmt)) {
                                                        break;
                                                    }
                                                }

                                                if (StringHelper.isNullOrEmpty(eachAmt) && "SAINTLSBZ0".equals(xmlReader.readedXElement.name)) {
                                                    //利息金额
                                                    eachAmt = xmlReader.readedXElement.getSingleTextNotNull("INTRST");
                                                } else if (StringHelper.isNullOrEmpty(eachAmt) && "EXICORRBZ1".equals(xmlReader.readedXElement.name)) {
                                                    //结汇
                                                    String[] amts = new String[]{"OUTAMT", "RCVAMT"};//OUTAMT卖出金额，RCVAMT买入金额
                                                    for (int i = 0; i < amts.length; i++) {
                                                        String outRcvAmt = xmlReader.readedXElement.getSingleTextNotNull(amts[i]);
                                                        if (StringHelper.hasAnyChar(outRcvAmt)) {
                                                            BigDecimal decAmtOutRcv = new BigDecimal(outRcvAmt);
                                                            BigDecimal decZero = new BigDecimal("0.00");
                                                            if (decAmtOutRcv.compareTo(decZero) != 0) {
                                                                eachAmt = outRcvAmt;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                                if (StringHelper.hasAnyChar(eachAmt)) {
                                                    eachRcptMp.amount = new BigDecimal(eachAmt);
                                                }else{
                                                    eachRcptMp.amount = new BigDecimal("0.00");
                                                }
                                                eachRcptMp.setBusDate(Format.Date8Format.parse(fdate));
                                                eachRcptMp.ownAct = actNum;
                                                //CPRRCRTNX1 对公转账退票回单（批量）；CPRRCRCVX1收款
                                                if ("CPRRCRTNX1".equals(xmlReader.readedXElement.name) || "CPRRCRCVX1".equals(xmlReader.readedXElement.name)) {
                                                    eachRcptMp.moneyWay = "2";
                                                } else if ("CSTRFPRTX0".equals(xmlReader.readedXElement.name) || "AGNCBPAYZ1".equals(xmlReader.readedXElement.name) || "CPRRCSNDX1".equals(xmlReader.readedXElement.name)) {
                                                    eachRcptMp.moneyWay = "1";//付款
                                                }
                                                eachRcptMp.keyName = "busRef";
                                                eachRcptMp.receiptNo = ISTNBR;
                                                //增加对方户名
                                                String[] oppActNames = new String[]{"RCVEAN", "RCVNAM", "BNFNAM", "ECLNAM", "TRXNM1"};
                                                for (int i = 0; i < oppActNames.length; i++) {
                                                    String oppActName = xmlReader.readedXElement.getSingleTextNotNull(oppActNames[i]);
                                                    if (StringHelper.hasAnyChar(oppActName)) {
                                                        eachRcptMp.oppActName=oppActName;
                                                        break;
                                                    }
                                                }
                                                //增加对方账号
                                                String[] oppActNums = new String[]{"RCVEAC", "BNFACC", "INSEAC","RCVACC", "EBKACC"};
                                                for (int i = 0; i < oppActNums.length; i++) {
                                                    String oppActNum = xmlReader.readedXElement.getSingleTextNotNull(oppActNums[i]);
                                                    if (StringHelper.hasAnyChar(oppActNum)) {
                                                        eachRcptMp.oppActNum=oppActNum;
                                                        break;
                                                    }
                                                }
                                                mapDetail.put(ISTNBR, eachRcptMp);
                                            }else if(mapDetail.containsKey(ISTNBR)){
                                            	ReceiptMapping eachRcptMp = mapDetail.get(ISTNBR);
                                            	for (int i = 0; i < refList.length; i++) {//潜在多个关联号也一并添加
                                                    if (StringHelper.hasAnyChar(refList[i])) {
                                                        eachRcptMp.addOtherBusRef(refList[i], eachRcptMp.receiptNo);
                                                    }
                                                }
                                            }
                                        } else if (!"INFO".equals(xmlReader.readedXElement.name) && !"CSRRCFDFZ1".equals(xmlReader.readedXElement.name)) {
                                            FGBiz.logTrace.infoNoTimeBank(reqHeader.bankCode, reqHeader.transType, "节点" + xmlReader.readedXElement.name + "无打印实例号<ISTNBR>");
                                        }
                                    /*
                					if("CPRRCSNDX1".equals(xmlReader.readedXElement.name)||"CPRRCRCVX1".equals(xmlReader.readedXElement.name)){
                						String NARTX1 = xmlReader.readedXElement.getSingleText("NARTX1");//对应历史明细YURREF
                    					String BUSNBR = xmlReader.readedXElement.getSingleText("BUSNBR");//对应历史明细NAREXT
                    					String ISTNBR = xmlReader.readedXElement.getSingleText("ISTNBR");//打印实例号
                    					if(StringHelper.hasAnyChar(NARTX1)){
                    						mapDetail.put(ISTNBR, NARTX1);
                    					}else if(StringHelper.hasAnyChar(BUSNBR)){
                    						mapDetail.put(ISTNBR, BUSNBR);
                    					}
                					}else if("AGNCBPAYZ1".equals(xmlReader.readedXElement.name)){
                						String TRSREF = xmlReader.readedXElement.getSingleText("TRSREF");
                						String ISTNBR = xmlReader.readedXElement.getSingleText("ISTNBR");
                						if(StringHelper.hasAnyChar(TRSREF)){
                    						mapDetail.put(ISTNBR, TRSREF);
                    					}
                					}else if(!"INFO".equals(xmlReader.readedXElement.name) && !"CSRRCFDFZ1".equals(xmlReader.readedXElement.name) && !unknowRcptType.contains(xmlReader.readedXElement.name)){
                						String ISTNBR = xmlReader.readedXElement.getSingleText("ISTNBR");//打印实例号
                						if(StringHelper.hasAnyChar(ISTNBR)){
                							String NARTX1 = xmlReader.readedXElement.getSingleText("NARTX1");
                    						String BUSNBR = xmlReader.readedXElement.getSingleText("BUSNBR");
                    						String TRSREF = xmlReader.readedXElement.getSingleText("TRSREF");
                    						String firstStr = StringHelper.getFirstNotEmptyTrim(NARTX1,BUSNBR,TRSREF);
                    						if(StringHelper.hasAnyChar(firstStr)){
                    							mapDetail.put(ISTNBR, firstStr);
                    							continue;
                    						}
                						}
                						//unknowRcptType.add(xmlReader.readedXElement.name);
                					}
                					*/
                                    }
                                } else {
                                    //记录不存在的，过滤消息，同一个文件不存在仅报一次
                                    if (!unExistDataFile.containsKey(dataFilePath)) {
                                        unExistDataFile.put(dataFilePath, dataFilePath);
                                        FGBiz.logTrace.infoBank(reqHeader.bankCode, reqHeader.transType, "账号" + actNum + "的" + fdate + "日回单数据文件" + dataFilePath + "尚未查回");
                                    }
                                }
                            }//是否已打印
                            mapNO.put(key1, mapDetail);
                        }
                        //根据账号-日期，取出回单记录列表
                        HashMap<String, ReceiptMapping> mapDetail2 = mapNO.get(key1);
                        if (mapDetail2.containsKey(receiptNO)) {//存在当前文件的打印实例号
                            ReceiptMapping rcptMp = mapDetail2.get(receiptNO);
                            String localPath = receiptFile.getAbsolutePath();
                            //String remotePath = StringHelper.getDirPathUsingSplitGiveUpLastOne(busRef, 3)+ File.separator+busRef+".jpg";
                            //WriteBankLogLn("文件"+eachName+"推送至远程路径"+remotePath);
                            //TcpReceiver retReceiver = dspClient.syncFile(localPath, "receipt",this.reqHeader.bankCode, remotePath);
                            //HelperResp saveResp = saveHelper.saveFile(this.reqHeader, FileType.receipt, localPath, busRef,Format.Date8Format.parse(fdate),actNum);
                            rcptMp.srcFile = StringHelper.getFileName(localPath);
                            if (receiptUploadShared) {
                                String ftpFilePath="";
                                String fileFlag="";
                                String filePath="";
                                int result = -1;
                                String fileName = new File(localPath).getName();
                                String tmpByDate = Format.Date8Format.format(new Date());
                                if (new File(localPath).exists()) {
                                    Calendar cal = Calendar.getInstance();
                                    cal.setTimeInMillis(new File(localPath).lastModified());
                                    cal.add(Calendar.DAY_OF_MONTH, 1);
                                    if (Format.Date8Format.format(cal.getTime()).compareTo(tmpByDate) >= 0) {
                                        tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + rcptMp.ownAct + "/";
                                        if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir) && !"sftp".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                            if(FGBiz.dspCenter.dspSet.receiptShareDir.startsWith("smb:")) {
                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(localPath, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                            fileFlag="共享目录";
                                            }
                                            else{
                                                tmpByDate =tmpByDate.replaceAll(reqHeader.bankCode + "/","");
                                                WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);

                                                Map<String,String> map ;
                                                map = FormSubmit.fileUpload(FGBiz.dspCenter.dspSet.receiptShareDir, actNum, localPath, tmpByDate, fileName, getCharset());
                                                WriteBankLogStep3(JSON.toJSONString(map));
                                                fileFlag = "微服务";
                                                if(map.keySet().size()!=0){
                                                    result = Integer.valueOf(map.get("respCode"));
                                                    tmpByDate =map.get("remotePath");
                                                }else{
                                                     result = -1;
                                                }
                                            }
                                        }else {
                                            //ftp/sftp服务器
                                            FtpSet ftpSet = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                            WriteBankLogLn("正在上传文件至ftp/sftp目录:" + ftpSet.upDir);
                                            //是否需要调整回单文件名
                                            if("false".equals(getBankConfig().getValueAsString("isEditFileName"))){
                                                WriteBankLogLn("==========文件更换文件名开始==========");
                                                String fileSuffix=fileName.substring(fileName.lastIndexOf("."));//.jpg
                                                String fileNameNew=new StringBuilder(reqHeader.bankCode).append("_").append(rcptMp.receiptNo).append("_").append(reqHeader.tenant).append(fileSuffix).toString();
                                                WriteBankLogLn("文件"+fileName+"名替换成文件名"+fileNameNew);
                                                fileName=fileNameNew;
                                                WriteBankLogLn("==========文件更换文件名结束==========");
                                            }
                                            //上传ftp/sftp服务器的地址
                                            if("false".equals(getBankConfig().getValueAsString("isCreateNewFile"))){//是否可以新建目录
                                                filePath=fileName;//否
                                            }else {
                                                filePath=tmpByDate+ fileName;//是
                                            }
                                            ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" + filePath;
                                            WriteBankLogLn("开始将回单"+localPath+"上传至"+ftpFilePath);
                                            if("sftp".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                                //上传至sftp
                                                result = FtpUtil.sftpUploading(ftpSet, localPath, ftpFilePath);
                                                fileFlag="sftp服务器";
                                            }else {
                                                //上传至ftp
                                                result = FtpUtil.ftpUploading(ftpSet, localPath, ftpFilePath);
                                                fileFlag="ftp服务器";
                                            }
                                        }
                                    }
                                }
                                if (result == 0 || result == 1) {
                                    tmpFileCount++;
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                    } else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    //推送数据给ATS处理
                                    json = new StringBuilder();
                                    json.append("{");
                                        json.append("\"actNum\":\"" + rcptMp.ownAct + "\",");
                                    String actCur = getBankConfig().getMapValueByKey("elereceiptAccountInfo",rcptMp.ownAct);
                                    if (StringHelper.isNullOrEmpty(actCur)){
                                        actCur = "1";
                                    }
                                    json.append("\"actCur\":\"" + actCur + "\",");
                                    json.append("\"receiptCode\":\"" + rcptMp.receiptNo + "\",");
                                    json.append("\"receiptType\":\"" + "" + "\",");
                                    json.append("\"receiptState\":\"" + "" + "\",");
                                    json.append("\"oppActName\":\"" + rcptMp.oppActName + "\",");
                                    json.append("\"oppActNum\":\"" + rcptMp.oppActNum + "\",");
                                    json.append("\"moneyway\":\"" + rcptMp.moneyWay + "\",");
                                    json.append("\"amount\":\"" + rcptMp.amount + "\",");
                                    json.append("\"tranSeqNo\":\"" + rcptMp.srcFile.split("_")[rcptMp.srcFile.split("_").length - 1].split("\\.")[0] + "\",");
                                    json.append("\"bnkReqNo\":\"" + rcptMp.srcFile.split("_")[rcptMp.srcFile.split("_").length - 1].split("\\.")[0] + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(String.valueOf(rcptMp.busDate))) + "\",");
                                    if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir) && !"sftp".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                        if("smb".equals(uploadType)){
                                        json.append("\"filePath\":\"" + tmpByDate + fileName + "\",");
                                        }else{
                                            json.append("\"filePath\":\"" + tmpByDate  + "\",");
//                                            json.append("\"filePath\":\""   + "\",");
                                        }
                                    }else {
                                        json.append("\"filePath\":\"" + filePath + "\",");//文件路径
                                    }
                                    json.append("\"fileType\":\"2\"");
                                    json.append("},");
                                    jsonList.add(json);
                                } else {
                                    WriteBankLogLn("上传文件至"+fileFlag+"失败，请检查共享目录配置是否正确");
                                }
                            } else {
                                HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, rcptMp, localPath);
                                
                                if (saveResp.isCompleted) {
                                    tmpFileCount++;
                                    listToDelete.add(receiptFile);
                                    //WriteBankLogLn("删除文件"+receiptFile.getName());
                                    //receiptFile.delete();

                                } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                	WriteBankLogLn(saveResp.sbMsg);
                                    WriteBankLogLn("连接服务器失败，终止本次推送");
                                    break;
                                } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                	WriteBankLogLn(saveResp.sbMsg);
                                    WriteBankLogLn("初始化类异常，终止本次推送");
                                    break;
                                }else{
                                	WriteBankLogLn(saveResp.sbMsg);
                                }
                            }
                			/*
                			if(retReceiver.isCompleted){
                				String retXml = new String(retReceiver.recBytes, retReceiver.contentStartIndex,retReceiver.contentLength, retReceiver.charsetName);
                				XmlTextReader retXmlRd = new XmlTextReader(retXml);
                				if("0".equals(retXmlRd.getSimpleText("RespCode"))){
                					WriteBankLogLn("文件"+eachName+"推送成功");
                					tmpFileCount++;
                					listToDelete.add(receiptFile);
                				}else{
                					WriteBankLogLn("文件"+eachName+"推送失败，响应报文："+retXml);
                				}
                			}
                			else{
                				WriteBankLogLn("文件"+eachName+"推送失败："+retReceiver.getConnMsg());
                				if(retReceiver.connState.equals(ConnState.FAIL)){
                					WriteBankLogLn("连接主DSP服务"+FGBiz.dspCenter.dspSet.receiptMainHostServer+"失败，终止本次推送");
                					break;
                				}
                			}
                			*/
                        } else {
                            double diffHours = DateHelper.getDifferHours(new Date(), lastMdDate);
                            if (diffHours < 72) {
                                //WriteBankLogLn("文件" + eachName + "找不到对应的业务参考号，暂不推送");
                            } else {//文件产生的时间超过100秒，可删除
                                WriteBankLogLn("删除文件" + eachName);
                                receiptFile.delete();
                            }
                        }
                    } else {
                    	double diffHours = DateHelper.getDifferHours(new Date(), lastMdDate);
                    	if (diffHours > 48) {
                    		//WriteBankLogLn("文件名" + eachName + "不符合预期");
                    		receiptFile.delete();
                    	}
                        continue;
                    }
                }
            }

            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            if(tmpFileCount == 0){
    			zeroNeedUpCount++;
    			long dalayMin = getDalayMin();
    			WriteBankLogLn("保存条数为0，增加轮询延时"+dalayMin+"分钟");
    		}else{
    			zeroNeedUpCount = 0;
    		}

            int delCount = 0;
            for (File delFile : listToDelete) {
                try {
                	Date mdDate = new Date(delFile.lastModified());
                	double chkHours = DateHelper.getDifferHours(new Date(), mdDate);
                	if(chkHours>24){//超过24小时再删
	                    //WriteBankLogLn("删除文件" + delFile.getName());
	                    delFile.delete();
	                    delCount++;
	                    //this.WriteBankLogLnNoTime("--删除完成");
                	}
                } catch (Exception ex) {
                    WriteBankLogLn(ex);
                }
            }
            WriteBankLogLn("成功删除了" + delCount + "个文件");

            if (receiptUploadShared && tmpFileCount > 0 && jsonList.size() > 0) {
                String sendStr = null;
                if(this.getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                    sendStr = "tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[";
                }else{
                    sendStr = "transType=downloadreceipt&data={\"rows\":[";
                }
                StringBuilder sendJson = new StringBuilder();
                String strValue = bankFront.getStrValueByFor("receiptDataCount", "");
                if (StringHelper.isNullOrEmpty(strValue)) {
                    strValue = "500";
                }
                Integer receiptDataCount = Integer.valueOf(strValue);
                for (int i = 0; i < jsonList.size(); i++) {
                    if ((i + 1) % receiptDataCount == 0 || i == jsonList.size() - 1) {
                        jsonList.get(i).deleteCharAt(jsonList.get(i).length() - 1);
                        sendJson.append(jsonList.get(i));
                        sendJson.append("]}");
                        String[] data ;
                        String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                        if("nbGateway".equals(receiptPushType)) {
                            WriteBankLogLn("3.推送给网关的数据" + sendStr + sendJson.toString().toString());
                            data= FormSubmit.receiptInfoSend(sendStr + sendJson.toString(),this);
                            if (data[0].length() == 0 && data[1].equals("ok")) {
                                WriteBankLogLn("5.推送数据到网关成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            } else {
                                WriteBankLogLn("5.推送数据到网关失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            }
                        }else{
                            WriteBankLogLn("3.推送给ATS的数据" + sendStr + sendJson.toString());
                            data = sendToATS(sendStr + sendJson.toString());
                            if (data[0].length() == 0 && data[1].equals("ok")) {
                                WriteBankLogLn("5.推送数据到ATS成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            } else {
                                WriteBankLogLn("5.推送数据到ATS失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            }
                        }
                        sendJson = new StringBuilder();
                    } else {
                        sendJson.append(jsonList.get(i));
                    }
                }
                WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }

    }

    public void getNewNotice() throws Exception {
        WriteBankLogLn("获取新通知");
        /*
    	 * <CMBSDKPGK>
<INFO>
<FUNNAM>GetNewNotice</FUNNAM>
<DATTYP>2</DATTYP>
<LGNNAM></LGNNAM>
</INFO>
</CMBSDKPGK>
    	 * */
        CMB01Header tmpBnkHeader = new CMB01Header();
        tmpBnkHeader.FUNNAM = "GetNewNotice";

        XmlTextWriter xmlWriter = new XmlTextWriter();
        writeCommonHeader(xmlWriter, tmpBnkHeader);
        xmlWriter.writeEndDocument();
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String returnCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                if (returnCode != null && "0".equals(returnCode)) {
                    int saveCount = 0;
                    NoticeDataHelper noticeHelper = new NoticeDataHelper(this.bankFront.tenant, new Date());
                    try{
                    	while (tmpBkReader.read("/CMBSDKPGK/NTQNTCGTZ")) {//NTQNTCGTZ //NTQNTCGTZ
                            XElement tmpRetNode = tmpBkReader.readedXElement;
                            //
                            String MSGTYP = tmpRetNode.getSingleTextNotNull("MSGTYP");
                            if (MSGTYP.toUpperCase().equals("NCDRTPAY")) {

                            	SinglePayNotice notice = new SinglePayNotice();
                                notice.reqSeqID = tmpRetNode.getSingleText("YURREF");

                                //业务处理结果 RTNFLG
                                notice.transState = "FIN+" + tmpRetNode.getSingleText("RTNFLG");
                                notice.payInfo = tmpRetNode.getSingleText("RTNDSP");
                                notice.payInfoCode = tmpRetNode.getSingleText("RTNDSP");
                                notice.outTransID = tmpRetNode.getSingleText("REQNBR");
                                notice.bankFrontCode = this.bankFront.bankCode;
                                if (tmpRetNode.getSingleText("TRSAMT") != null) {
                                	notice.transAmt = tmpRetNode.getSingleText("TRSAMT");
                                }
                                try {
                                	
                                	int rowsAff = noticeHelper.insertOrUpdate(notice, reqHeader.bankCode);
                                    if (rowsAff>0) {
                                        saveCount++;
                                    }else{
                                    	WriteBankLogLn(notice.reqSeqID + "保存影响行数："+saveCount);
                                    }
                                } catch (Exception ex) {
                                    WriteBankLogLn(ex, notice.reqSeqID + "保存发生异常");
                                }
                            }
                        }
                    }catch(Exception ex){
                    	WriteBankLogLn(ex);
                    }finally{
                    	noticeHelper.close();
                    }
                    
                    WriteBankLogLn("共保存了" + saveCount + "条结果通知");
                }
            } else {
                WriteBankLogLn(tmpSbMsg.toString());
            }
        } else {
            WriteBankLogLn(tmpStrRet[0] + "-" + tmpStrRet[1]);
        }
    }
}
